import { useEffect, useState } from 'react';
import Taro, { useDidShow, useLoad } from '@tarojs/taro';
import { View, Text } from '@tarojs/components';
import { AtActionSheet, AtActionSheetItem, AtButton } from 'taro-ui';
import { useUserStore } from '@/business/store/user/login';
import { contactStore } from '@/business/store/contact/contact';
import SafePhoneModal from '@/components/SafePhoneModal';
import UserCard from '@/components/UserCard';
import ScrollList from '@/components/ScrollList';
import EmptyPage from '@/components/EmptyPage';
import cssModule from './index.module.scss';
import SearchBox from '@/pages/index/components/SearchBox';
import { deleteFriend, deleteGroup, friendFroups } from '@/business/services/contact';

/**
 * @description 我的好友
 * @author Shawn
 */

export default function MyFriends({ updateGroup }: { updateGroup: boolean }) {
  const useUser = useUserStore()
  const [currentPage, setCurrentPage] = useState(1);
  const [activeGroup, setActiveGroup] = useState('全部好友');
  const friendList = contactStore((state) => state.friendList);
  const groupList = contactStore((state) => state.groupList);
  const applyFriendList = contactStore((state) => state.applyFriendList);
  const isDataLoaded = contactStore((state) => state.isDataLoaded);
  const hasMore = contactStore((state) => state.hasMore);
  const [showPhone, setShowPhone] = useState(false);

  // 获取好友名单
  const getFriendList = async () => {
    setCurrentPage(1);
    await contactStore.getState().getFriendList({ current: 1, size: 10 });
  }

  // 上拉加载好友名单
  const handleOnScrollToLower = async () => {
    if (friendList.length % 10 !== 0) return;
    const nextPage = currentPage + 1;
    setCurrentPage(nextPage);
    await contactStore.getState().handlePullUpOrDown({ current: nextPage, size: 10 });
  };

  // 获取申请好友名单
  const getApplyFriendList = async () => {
    await contactStore.getState().getApplyFriendList();
  }

  // 跳转到申请好友页面
  const handleApplyFriend = () => {
    if (useUser?.vipInfo?.vipLevelId !== '001') {
      Taro.navigateTo({
        url: `/subPackages/equity/index`,
      });
      return
    }
    Taro.navigateTo(
      {
        url: '/subPackages/applyFriend/index'
      }
    );
  }

  // 跳转到搜索好友页面
  const handleSearch = () => {
    Taro.navigateTo(
      {
        url: `/subPackages/searchFriend/index`
      }
    );
  };

  // 切换分组
  const handleGroupChange = (groupName: string) => {
    return () => {
      console.log(groupName, 'groupName')
      setActiveGroup(groupName);
      // 根据分组获取好友名单
      // getFriendList();
    }
  };

  const [isActionSheetOpened, setIsActionSheetOpened] = useState(false);
  const [isActionSheetOpened2, setIsActionSheetOpened2] = useState(false);
  const [isSafePhoneModalOpened, setIsSafePhoneModalOpened] = useState(false);
  const [contactMobile, setContactMobile] = useState(''); // 联系电话
  const [contactUserID, setContactUserID] = useState(''); // 用户userID

  // 个人空间
  const handlePerson = (item: any) => {
    if (useUser?.vipInfo?.vipLevelId === '001') {
      setIsActionSheetOpened(false);
      Taro.navigateTo({
        url: `/subPackages/userDetail/index?id=${contactUserID}`
      });
    } else {
      Taro.navigateTo({
        url: `/subPackages/equity/index`,
      });
    }
  };

  // 拨打电话
  const handleCall = () => {
    setIsActionSheetOpened(false);
    // setIsSafePhoneModalOpened(true);
    Taro.makePhoneCall({
      phoneNumber: contactMobile,
      success: () => {
      },
      fail: (err) => {
        console.error('拨打电话失败:', err)
        Taro.showToast({
          title: '拨打失败',
          icon: 'none'
        })
      }
    })
  };

  // 发送消息
  const handleSendMsg = () => {
    setIsActionSheetOpened(false);
    if (!contactUserID) return
    Taro.navigateTo({
      url: '/subPackages/chatlist/index' + `?conversationID=C2C${contactUserID}`
    })
  };

  const [name, setName] = useState('')
  const [headImg, setHeadImg] = useState('')
  const [remark, setRemark] = useState('')

  const handleClick3 = (item: any) => {
    return () => {
      if (useUser?.vipInfo?.vipLevelId !== '001') {
        Taro.navigateTo({
          url: `/subPackages/equity/index`,
        });
        return
      }
      setIsActionSheetOpened(true);
      setContactUserID(item?.id ?? '')
      setContactMobile(item?.contactMobile ?? '');
      setName(item?.name ?? '')
      setHeadImg(item?.headImg ?? '')
      setRemark(item?.remark ?? '')
      setShowPhone(item.virtualNumberIsEnable ?? false)
    }
  };

  const handleRemark = () => {
    setIsActionSheetOpened(false)
    Taro.navigateTo({
      url: `/subPackages/remark/index?name=${name}&headImg=${headImg}&friendId=${contactUserID}&remark=${remark}`
    })
  }

  const handleDeleteFriend = async () => {
    const res = await deleteFriend(contactUserID)
    if (res.success) {
      contactStore.getState().deleteFriend(contactUserID)
      Taro.showToast({ title: '好友删除成功', icon: 'success' })

      setIsActionSheetOpened(false)
    }
  }

  const onAddGroup = () => {
    if (useUser?.vipInfo?.vipLevelId !== '001') {
      Taro.navigateTo({
        url: `/subPackages/equity/index`,
      });
      return
    }
    Taro.navigateTo({
      url: '/subPackages/groups/index'
    })
  }

  const [ids, setIds] = useState<string>('')
  const [groupId, setGroupId] = useState('')
  const [groupName, setGroupName] = useState('')
  const onHandleGroup = (ids: string[], id: string, name) => {
    return () => {
      if (useUser?.vipInfo?.vipLevelId !== '001') {
        Taro.navigateTo({
          url: `/subPackages/equity/index`,
        });
        return
      }
      setIsActionSheetOpened2(true)
      setIds(ids.join(','))
      setGroupId(id)
      setGroupName(name)
    }
  }

  const handleAddGroup = () => {
    setIsActionSheetOpened2(false)
    Taro.navigateTo({
      url: '/subPackages/groups/index'
    })
  }

  const handleDeleteGroup = async () => {
    const res = await deleteGroup(groupId)
    if (res.success) {
      setIsActionSheetOpened2(false)
      Taro.showToast({ title: '删除成功', icon: 'success' });
    }
  }

  const handleEditGroup = () => {
    setIsActionSheetOpened2(false)
    Taro.navigateTo({
      url: '/subPackages/groups1/index?groupId=' + groupId + '&type=edit' + '&groupName=' + groupName + '&ids=' + ids
    })
  }

  const handleAddFriend = () => {
    setIsActionSheetOpened2(false)
    Taro.navigateTo({
      url: '/subPackages/groups/index?type=addMember&ids=' + ids + '&groupId=' + groupId
    })
  }

  const handleReport = () => {
    setIsActionSheetOpened(false)
    Taro.navigateTo({
      url: `/subPackages/report/index?id=${contactUserID}`,
    });
  }

  return (
    <View className={cssModule.container}>
      <View className={cssModule.listBox}>
        {/* 选项卡组件 */}
        <View className={cssModule.tabsBox}>
          {/* 申请好友提示 */}
          {
            (
              <View className={cssModule.applyBox} onClick={handleApplyFriend}>
                <Text className={cssModule.applyTitle}>申请好友</Text>
                <View className={cssModule.applyContent}>
                  <Text>
                    有 <Text className={cssModule.applyCount}>{applyFriendList.length}</Text> 位申请添加好友
                    <Text className={cssModule.applyArrow}> &gt; </Text>
                  </Text>
                </View>
              </View>
            )
          }
          {/* 搜索组件 */}
          <View className={cssModule.searchBox} onClick={handleSearch}>
            <SearchBox />
          </View>
          {/* 好友分组 */}
          <View className={cssModule.groupBox}>
            <View
              className={`${cssModule.groupText} ${activeGroup === '全部好友' ? cssModule.active : ''}`}
              onClick={handleGroupChange('全部好友')}
            >
              全部好友
            </View>
            <View
              className={`${cssModule.groupText} ${activeGroup === '好友分组' ? cssModule.active : ''}`}
              onClick={handleGroupChange('好友分组')}
            >
              好友分组
            </View>
          </View>
          {/* 列表容器组件 */}
          {activeGroup === '全部好友' &&
            <View className={cssModule.scrollList}>
              <ScrollList childrenNode={
                <>
                  {
                    (!isDataLoaded && (!friendList || friendList.length === 0)) ? (
                      <EmptyPage defaultName='' />
                    ) : (
                      friendList?.map((item: any, idx: number) => (
                        <View className={cssModule.listViewCard} key={item.id ?? idx} onClick={handleClick3(item)}>
                          <UserCard item={item} />
                        </View>
                      ))
                    )
                  }
                </>
              }
                height={`100%`}
                onScrollToLower={handleOnScrollToLower}
                hasMore={hasMore}
                isDataLoaded={isDataLoaded}
              />
            </View>
          }
          {activeGroup === '好友分组' &&
            (groupList.length === 0 ? <AtButton className={cssModule.addGroupBtn} type='primary' onClick={onAddGroup}>添加分组</AtButton> :
              <View className={cssModule.scrollList}>
                <ScrollList childrenNode={
                  <>
                    {
                      groupList?.map((item: any, idx: number) => (
                        <View className={cssModule.listViewCard} key={item.id ?? idx}>
                          <View className={cssModule.listViewItemCard}>
                            <View className={cssModule.groupNameText}>
                              <View>{item.groupName}（{item.friendCount}人）</View>
                              <View onClick={onHandleGroup(item.friends.map(item1 => (item1.id)), item.id, item.groupName)}>···</View>
                            </View>
                            {
                              item.friends.map(item1 => (
                                <View onClick={handleClick3(item)}>
                                  <UserCard item={item1} />
                                </View>

                              ))
                            }

                          </View>
                        </View>
                      ))
                    }
                  </>
                }
                  height={`100%`}
                  onScrollToLower={handleOnScrollToLower}
                  hasMore={hasMore}
                  isDataLoaded={isDataLoaded}
                />
              </View>)
          }
        </View>
      </View>

      {/* 联系TA */}
      <AtActionSheet
        isOpened={isActionSheetOpened}
        cancelText='取消'
        onClose={() => setIsActionSheetOpened(false)}
        onCancel={() => setIsActionSheetOpened(false)}
      >
        {activeGroup === '全部好友' && <AtActionSheetItem onClick={handleRemark}>备注/分组</AtActionSheetItem>}
        <AtActionSheetItem onClick={handlePerson}>个人空间</AtActionSheetItem>
        {showPhone && <AtActionSheetItem onClick={handleCall}>拨打对方电话</AtActionSheetItem>}
        <AtActionSheetItem onClick={handleSendMsg}>发送消息</AtActionSheetItem>
        <AtActionSheetItem onClick={handleDeleteFriend}>删除好友</AtActionSheetItem>
        <AtActionSheetItem onClick={handleReport}>举报Ta</AtActionSheetItem>
        {/* <AtActionSheetItem onClick={handleSendMsg}>加入黑名单</AtActionSheetItem> */}

      </AtActionSheet>

      <AtActionSheet
        isOpened={isActionSheetOpened2}
        cancelText='取消'
        onClose={() => setIsActionSheetOpened2(false)}
        onCancel={() => setIsActionSheetOpened2(false)}
      >
        <AtActionSheetItem onClick={handleAddFriend}>添加组员</AtActionSheetItem>
        <AtActionSheetItem onClick={handleEditGroup}>编辑分组</AtActionSheetItem>
        <AtActionSheetItem onClick={handleAddGroup}>新增分组</AtActionSheetItem>
        <AtActionSheetItem onClick={handleDeleteGroup}>删除分组</AtActionSheetItem>
        {/* <AtActionSheetItem onClick={handleSendMsg}>加入黑名单</AtActionSheetItem>
        <AtActionSheetItem onClick={handleCall}>举报Ta</AtActionSheetItem> */}
      </AtActionSheet>

      {/* 安全号弹窗 */}
      <SafePhoneModal
        contactMobile={contactMobile}
        isOpened={isSafePhoneModalOpened}
        onClose={() => setIsSafePhoneModalOpened(false)}
      />
    </View>
  )
}
